
import type {Product} from "../typing/product"
import {getProductList,addProduct,delProduct,updateProduct} from "../http/product"

import productStore from "../store/productStore"
import { ElMessage } from "element-plus"
import {useRouter} from "vue-router"
export interface iProductM{
    productListHook:()=>{},
    addProductHook:(product:Product)=>{},
    updateProductHook:(product:Product,objectId:string)=>{},
    deleteProductHook:(objectId:string)=>{},
    searchProductHook:(name:string)=>{}
}
//显示生产信息
//添加
//修改
//删除
//查询
//闭包
export function productM():iProductM{
    const router=useRouter();
    const product_Store=productStore();
    
async function productListHook(){
    const result=await getProductList();
    console.log("hook",result.data.results)
    product_Store.setLists(result.data.results);
    
}
async function addProductHook(product:Product){
    try{
        const result=await addProduct(product.no,product.productId,product.productName,product.productPlan,product.objectId);
        getProductList();
         if(result.data?.objectId){
            ElMessage({
                message:'添加成功',
                type:'success'
            })
            router.push('/home/product')
        }else{
            ElMessage({
                message:'保存失败',
                type:'error'
            })
        }
    }catch{

    }
}

async function updateProductHook(product:Product,objectId:string){
    try{
        console.log("1")
        const result=await updateProduct(
               
            product.no,
            product.productId,
            product.productName,
            product.productPlan,
            objectId
        )
        console.log(result.data)
        if(result.data?.objectId){
        ElMessage({
            message:'编辑成功',
            type:'success'
        })
        router.push('/home/product')
    }else{
        ElMessage({
            message:'编辑失败',
            type:'error'
        })
    }
    }catch(e){
        console.log("error")
        console.log(e)
    }
}

function deleteProductHook(objectId:string){
    delProduct(objectId).then(res=>{
        console.log(res);
        ElMessage({
            type: 'success',
            message: '删除成功',
          })
          productListHook()
    }).catch(err=>{
        console.log(err)
        ElMessage({
            type: 'error',
            message: '删除失败',
          })
    })
}

function searchProductHook(name:string){
    
}

return {
    productListHook,
    addProductHook,
    updateProductHook,
    deleteProductHook,
    // searchProductHook
}
}